/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_orm.htm
 *
 * Zhiqim ORM is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.orm;

import java.sql.Connection;
import java.sql.SQLException;

import org.zhiqim.kernel.transaction.Transaction;
import org.zhiqim.kernel.transaction.TransactionAbstracter;

/**
 * 实现事务接口，包括提交、回滚、关闭以及判断是否已提交和已回滚，该类只由事务管理器创建
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class ORMTransaction extends TransactionAbstracter
{
    private Connection conn = null;
    private boolean autoCommit = true;
    
    public ORMTransaction(String id, Connection conn)
    {
        super(id);
        this.conn = conn;
    }
    
    /** 开始一个事务 */
    public Transaction begin() throws SQLException
    {
        autoCommit = conn.getAutoCommit();
        if (autoCommit)
            conn.setAutoCommit(false);
        return this;
    }

    /** 提交一个事务 */
    public void commit() throws SQLException
    {
        conn.commit();
        super.setCommitted();
    }

    /** 回滚一个事务 */
    public void rollback() throws SQLException
    {
        conn.rollback();
        super.setRollbacked();
    }
    
    /** 关闭一个事务 */
    public void close() throws SQLException
    {
        conn.setAutoCommit(autoCommit);
        conn.close();
        
        super.setClosed();
    }
}
